package cn.lcsjsxy.yxz.day.Practice.Thread;

//线程中断
public class Practice5 {
    public static void main(String[] args) {

        //创建一个线程,该线程不断打印计数,当主线程中断它时,能够优雅的退出!

        //创建计数线程
        Thread countingThread = new Thread(() -> {
           int count = 0;
           //检查线路是否被中断
            while (!Thread.currentThread().isInterrupted()){
                System.out.println("计数: " + count++);
                try {
                    Thread.sleep(500);
                }catch (InterruptedException e){
                    //捕获中断异常,重新设置中断状态
                    Thread.currentThread().interrupt();
                    System.out.println("中断");
                }
            }
            System.out.println("退出");
        });
        countingThread.start();

        //主线程休眠3秒后中断计数线程
        try {
            Thread.sleep(3000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }

        countingThread.interrupt();
    }
}
